<template>
    <el-drawer v-model="drawer" title="任务详情" size="1000">
        <el-skeleton v-if="drawer" animated :loading="loading" :throttle="300">
            <template #template> <SkeletonTemp /> </template>
            <template #default>
                <div class="task_detail_title">
                    <div class="task_title">
                        {{ renderText(detail.basic_info?.task_name) }}
                        <div class="task_type">
                            {{ renderText(detail.basic_info?.type_name) }}
                        </div>
                    </div>
                </div>
                <div class="task_detail_label">基本信息</div>
                <el-descriptions :column="2">
                    <el-descriptions-item label="所属模块:">
                        {{ renderText(detail.basic_info?.module_type_name) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="操作者:">
                        {{ renderText(detail.basic_info?.created_uid_name) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="创建时间:">
                        {{ renderText(detail.basic_info?.created_at) }}
                    </el-descriptions-item>
                    <el-descriptions-item v-if="isTypeTask('IMPORT')" label="重复数据处理方式:">
                        {{ renderText(renderName(detail.basic_info?.method)) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="开始时间:">
                        {{ renderText(detail.basic_info?.begin_time) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="结束时间:">
                        {{ renderText(detail.basic_info?.finish_time) }}
                    </el-descriptions-item>
                    <el-descriptions-item v-if="isTypeTask('SUBTASK')" label="子任务数:">
                        {{ renderText(detail.basic_info?.line_total) }}
                    </el-descriptions-item>
                    <el-descriptions-item v-if="isRenderUpdate" label="更新信息:" class-name="update_info">
                        {{ renderText(detail.basic_info?.update_info) }}
                    </el-descriptions-item>
                    <!-- 多级任务显示 任务统计（成功+失败）    其他显示 总数（XX条+成功+失败） -->
                    <el-descriptions-item
                        v-if="!isTypeTask('EXPORT')"
                        :label="isTypeTask('SUBTASK') ? '任务统计:' : '总数:'">
                        <span v-if="!isTypeTask('SUBTASK')" class="total_num">
                            {{ renderText(detail.basic_info?.line_total) }} <span>条</span>
                        </span>
                        <span class="success_num">
                            <span>成功：</span>{{ renderText(detail.basic_info?.line_total_success) }} <span>条</span>
                        </span>
                        <span class="fail_num">
                            <span>失败：</span>{{ renderText(detail.basic_info?.line_total_fail) }} <span>条</span>
                        </span>
                    </el-descriptions-item>
                </el-descriptions>

                <div class="task_detail_label table_lable">
                    <span>{{ ListTitleName.get(detail.basic_info.type) }}</span>
                    <el-button v-if="isRenderExport" plain @click="toExport">导出</el-button>
                </div>

                <div v-if="isTypeTask('TRANSFER') && detail.basic_info.is_job" class="inherit_task">
                    注：针对离职继承、在职继承任务，由于需要客户手动确认是否同意交接，实际接替状态请在&lt;员工中心-离职继承/在职继承&gt;查看，当前状态仅表示客户转移任务推送成功。
                </div>
                <div class="task_table">
                    <ZwTable
                        ref="tableRef"
                        class="table-box"
                        :show-pagination="!isTypeTask('SUBTASK')"
                        :option="tableOption"
                        :row-key="getRowKey"
                        :fetch-params="state.searchParams"
                        :fetch-api="fetchApi()" />
                </div>
            </template>
        </el-skeleton>
    </el-drawer>
</template>

<script lang="ts" setup>
import ZwTable from '@/components/zw/table/Table';
import { ElMessage } from 'element-plus';
import { ref, reactive, computed, watch, nextTick } from 'vue';
import { cloneDeep } from 'lodash';
import SkeletonTemp from './template/SkeletonTemp.vue';
import { getAsyncDetailInfo, exportAsyncTask, getSubTaskList } from '@/api/channelconfig/asyncTask';
import { downloadFile } from '@/utils/utils';
import {
    tableColumnOption,
    ListAttributeName,
    ListTitleName,
    renderText,
    taskType
} from '../configuration/detailTableOption';

const props = defineProps({
    modelValue: Boolean,
    id: [Number, String]
});
const emit = defineEmits(['update:modelValue']);

const drawer = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    }
});
watch(
    () => props.modelValue,
    val => {
        if (val) {
            reset();
        }
    }
);

/* =======================详情数据======================== */
const detail = reactive<TaskDetail>({
    basic_info: { type: 0 }
});
// 骨架屏loading
const loading = ref(true);

// 是否是指定任务类型的Type
const isTypeTask = function (type: string | string[]) {
    return typeof type === 'string'
        ? detail.basic_info.type === taskType[type]
        : type.some(item => detail.basic_info.type == taskType[item]);
};

// 导出
const toExport = async () => {
    const { url } = (await exportAsyncTask({ id: props.id })) || {};
    url ? downloadFile(url) : ElMessage.warning('暂无文件url');
};
const isRenderExport = computed(() => {
    return isTypeTask('IMPORT') && detail.import_data?.total;
});

const isRenderUpdate = computed(() => {
    return isTypeTask('UPDATE') && detail.basic_info?.module_type != 16;
});

// 重复数据处理方式
const renderName = (method?: string) =>
    ({
        1: '保留新数据',
        2: '保留老数据',
        3: '补充老数据空白项'
    }[method ?? '']);
/* =======================详情数据======================== */

/* ============================表格-start=========================== */
const defaultParams = {
    id: props.id
};
const tableRef = ref();

// 表格参数
const state = reactive({
    searchParams: cloneDeep(defaultParams)
});
// 重制详情
const reset = () => {
    state.searchParams = { id: props.id };
};

// 自定义表格查询接口
const fetchApi = () => {
    return (params: any) => {
        return new Promise((resolve, reject) => {
            try {
                loading.value = true;
                getAsyncDetailInfo(params).then((res: TaskDetail) => {
                    Object.assign(detail, res);
                    if (isTypeTask('SUBTASK')) {
                        // 获取子任务数据
                        getSubTaskList({ id: props.id }).then((data: any) => {
                            resolve(Array.isArray(data) ? { data, total: 0 } : { data: [], total: 0 });
                        });
                    } else {
                        const data = res[ListAttributeName.get(res.basic_info.type) || ''];
                        resolve(Array.isArray(data) ? { data: [], total: 0 } : data || { data: [], total: 0 });
                    }
                });
            } catch (err) {
                // 应对接口报错的情况
                detail.basic_info = { type: 0 };
                resolve({ data: [], total: 0 });
                reject(err);
            } finally {
                getTableH();
                loading.value = false;
            }
        });
    };
};
// 列配置项
const tableOption = computed(() => {
    const { type, is_job, is_tag, module_type } = detail.basic_info;
    return tableColumnOption({ type, is_job, is_tag, module_type });
});
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
const getRowKey = isTypeTask('IMPORT') ? (row: any) => row.line_num : (row: any) => row.id;
/* ============================表格-end============================ */

interface TaskDetail {
    basic_info: {
        task_name?: string;
        type_name?: string;
        type: number;
        module_type_name?: string;
        created_uid_name?: string;
        created_at?: string;
        method?: string;
        update_info?: string;
        begin_time?: string;
        finish_time?: string;
        line_total?: number;
        line_total_success?: number;
        line_total_fail?: number;
        is_job?: boolean;
        is_tag?: boolean;
        module_type?: string | number;
    };
    import_data?: any;
}
</script>

<style lang="scss" scoped>
@import './detail.scss';

:deep(.subtask_status_point) {
    --status-bgcolor: #ffd500;
    &::before {
        display: inline-block;

        width: 8px;
        height: 8px;
        margin-right: 8px;
        content: '';

        border-radius: 4px;
        background-color: var(--status-bgcolor);
    }
}
</style>
